/**
* 双击可输入的文本框组件
*/

import React, { Component, PropTypes } from 'react'

class InputCompoment extends Component {
  constructor(props, context) {
    super(props, context);
    let textContent='';
    if(this.props.text!=null) textContent=this.props.text;
    this.state = {
      text: textContent
    }
  }

  handleSubmit(e) {
    const text = e.target.value.trim()
    if (e.which === 13) {
      this.props.onSave(text)
    }
  }

  handleChange(e) {
    this.setState({ text: e.target.value })
  }

  handleBlur(e) {
    this.props.onSave(e.target.value)
  }

  render() {
  	let length=this.props.length;
  	if(length==null) length=10;
    return (
      <input  type="text" autoFocus="true" size={length}
        value={this.state.text} onBlur={this.handleBlur.bind(this)}
        onChange={this.handleChange.bind(this)} onKeyDown={this.handleSubmit.bind(this)} />
    )
  }
}

const blankLabelStyle={display:'inline-block', width:'50px',height:'14px'};
const defaultLableStyle={display:'inline-block', width:'auto'};
class TextInput extends Component {
  constructor(props, context) {
    super(props, context);
    let labelStyle=defaultLableStyle;
    if(!this.props.text) labelStyle=blankLabelStyle;
    this.state = {
      editing: false,
      text:this.props.text,
      labelStyle:labelStyle
    }
    this.editable=true;//默认双击可编辑
    if(this.props.editable!=null) this.editable=this.props.editable;
  }

  handleDoubleClick() {
  	if(this.editable)
    	this.setState({ editing: true })
  }

  handleSave(text) {
    this.props.handleEdit(text);
    let labelStyle=defaultLableStyle;
    if(text.trim()=='') labelStyle=blankLabelStyle;
    this.setState({ editing: false,text:text,labelStyle:labelStyle });
  }

  render() {
    let element;
    if (this.editable && this.state.editing) {
      element = (
        <InputCompoment text={this.props.text} editing={this.state.editing} onSave={ text => this.handleSave(text)} length={this.props.length} />
      )
    } else {
      element = (
        <label onDoubleClick={this.handleDoubleClick.bind(this)} style={this.state.labelStyle}>
            {this.props.text}
        </label>
      )
    }
    let prespan='';
    if(this.props.addpre!=null){
    	prespan=(<span style={{ marginRight:5,color:''}}>{this.props.addpre}</span>);
    }
    return (
      <span>{prespan}{element}</span>
    )
  }
}

/**
 * 参数 text:文本框初始显示的值
 *      handleEdit: 值修改后调用的处理方法
 *      length：输入框的长度大小,input的size属性，默认为10
 *      addpre: 前缀信息，默认为空
 *      editable：双击是否可以编辑，默认为true,可编辑
 */
export default TextInput;

